<template>
	<view class="other-login u-f-ac">
	
		<!-- #ifdef MP-WEIXIN -->
		<button type="primary" open-type="getUserInfo" @getuserinfo="mpGetUserInfo">微信登录</button>
		<!-- #endif -->
	</view>
</template>

<script>
	export default {
		props: {
			noback: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				providerList: []
			}
		},
		methods: {
			// #ifdef MP-WEIXIN
			mpGetUserInfo(result) {
				uni.showLoading({
					title: '登陆中...', mask: true
				});
				// 获取 userinfo 失败
				if (result.detail.errMsg !== 'getUserInfo:ok') {
					uni.hideLoading();
					uni.showModal({
						title: '获取用户信息失败',
						content: '错误原因:' + result.detail.errMsg,
						showCancel: false
					});
					return;
				}
				// 获取到 userinfo
				let userinfo = result.detail.userInfo;
				uni.login({
					provider: 'weixin',
					success: (res) => {
						// console.log(res.code) // 获取到 code
						// 向服务端登录
						this.MpLogin({
							url: "/user/wxlogin",
							code:res.code,
							nickName:userinfo.nickName,
							avatarUrl:userinfo.avatarUrl
						})
					},
					complete: () => {
						uni.hideLoading();
					}
				})
			},
			// #endif
			
			// 向服务器登录
			MpLogin(options){
				this.$http.post(options.url,{
					code:options.code,
					nickName:options.nickName,
					avatarUrl:options.avatarUrl
				}).then(data=>{
					let [err2,res2] = data;
					// 登录失败
					if (!this.$http.errorCheck(err2,res2)){
						return false;
					}
					// 登录成功 保存状态
					this.User.token = res2.data.data.token;
					this.User.userinfo = this.User.__formatUserinfo(res2.data.data);
					// 本地存储
					uni.setStorageSync("userinfo",this.User.userinfo);
					uni.setStorageSync("token", this.User.token);
					
					// 获取用户相关统计
					// 连接socket

					// 成功提示
					uni.showToast({ title: '登录成功' });
					// 登录成功，重新加载数据
					this.$emit('logining')
					if (!this.noback) {
						uni.navigateBack();
					}
				});
			},
		}
	}
</script>

<style>
</style>
